
 <?
/*
 * PHP Freaks Code Library
 * http://www.phpfreaks.com/quickcode.php
 *
 * Title: ASCII to Binary to ASCII Conversion Functions
 * Version: 1.0
 * Author: Adam Goossens aka(agoossens)
 * Date: Monday, 12/15/2003 - 06:10 AM
 *
 * 
 *
 * NOTICE: This code is available from PHPFreaks.com code Library.
 *         This code is not Copyrighted by PHP Freaks. 
 *
 *         PHP Freaks does not claim authorship of this code.
 *
 *         This code was submitted to our website by a user. 
 *
 *         The user may or may not claim authorship of this code.
 *
 *         If there are any questions about the origin of this code,
 *         please contact the person who submitted it, not PHPFreaks.com!
 *
 *         USE THIS CODE AT YOUR OWN RISK! NO GUARANTEES ARE GIVEN!
 *
 * SHAMELESS PLUG: Need WebHosting? Checkout WebHost Freaks:
 *                 http://www.webhostfreaks.com
 *                 WebHosting by PHP Freaks / The Web Freaks!
*/


// *    Description / Example:
// *    
// *    A few people have asked how to turn an ASCII string into it\'s binary representation. These functions will do it both ways - as long as the binary input string is not corrupted.
// *    
// *    Assumes two things:
// *    1) Perfect string condition with a whole number of bytes in the binary input.
// *    2) No wide characters (can\'t handle that).
// *    
// *    Has minimalistic support for systems that have more (or less) than 8 bits per byte.

?>

<?php
// convert an input string into it's binary equivalent.
function asc2bin($inputString, $byteLength=8)
{
	$binaryOutput = '';
	$strSize = strlen($inputString);

	for($x=0; $x<$strSize; $x++)
	{
		$charBin = decbin(ord($inputString{$x}));
		$charBin = str_pad($charBin, $byteLength, '0', STR_PAD_LEFT);
		$binaryOutput .= $charBin;
	}

	return $binaryOutput;
}

// convert a binary representation of a string back into it's original form.
function bin2asc($binaryInput, $byteLength=8)
{
	if (strlen($binaryInput) % $byteLength)
	{
		return false;
	}
	
	// why run strlen() so many times in a loop? Use of constants = speed increase.
	$strSize = strlen($binaryInput);
	$origStr = '';

	// jump between bytes.
	for($x=0; $x<$strSize; $x += $byteLength)
	{
		// extract character's binary code
		$charBinary = substr($binaryInput, $x, $byteLength);
		$origStr .= chr(bindec($charBinary)); // conversion to ASCII.
	}
	return $origStr;
}

$inputString = "An input string, complete with punctuation!";

$binOut = asc2bin($inputString);
printf("Input String: %s\nBinary Version: %s\n",$inputString, $binOut);

$ascOut = bin2asc($binOut);
printf("Input Binary: %s\nOutput ASCII: %s\n",$binOut, $ascOut);
?>